const EventEmitter = require("events");
const os = require("os");

/**
 * 网络连接检测器
 * 用于检测网络连接状态变化
 */
class NetworkDetector extends EventEmitter {
  constructor(ip, checkInterval = 5000) {
    super();
    this.ip = ip;
    this.checkInterval = checkInterval;
    this.isOnline = true; // 初始状态设为在线
    this.intervalId = null;
  }

  /**
   * 开始检测网络连接状态
   */
  start() {
    // 清除现有的检测定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }

    // 定期检查网络状态
    this.intervalId = setInterval(() => {
      this._checkNetworkStatus();
    }, this.checkInterval);

    // 立即检查一次
    this._checkNetworkStatus();
  }

  /**
   * 停止检测网络连接状态
   */
  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }

  /**
   * 检查网络状态
   * @private
   */
  _checkNetworkStatus() {
    try {
      const networkInterfaces = os.networkInterfaces();
      let isNetworkAvailable = false;

      // 检查是否有活动的网络接口
      Object.keys(networkInterfaces).forEach((interfaceName) => {
        const interfaces = networkInterfaces[interfaceName];
        interfaces.forEach((interfaceInfo) => {
          if (!interfaceInfo.internal && interfaceInfo.family === "IPv4") {
            isNetworkAvailable = true;
          }
        });
      });

      // 如果网络状态发生变化，发出相应事件
      if (isNetworkAvailable && !this.isOnline) {
        this.isOnline = true;
        this.emit("networkRestored");
      } else if (!isNetworkAvailable && this.isOnline) {
        this.isOnline = false;
        this.emit("networkLost");
      }
    } catch (error) {
      console.error("检查网络状态时出错:", error);
    }
  }

  /**
   * 检查特定IP是否可达
   * 使用简单的TCP连接检测
   */
  async checkIpReachable(ip, port, timeout = 3000) {
    const net = require("net");
    return new Promise((resolve) => {
      const socket = new net.Socket();
      let connected = false;

      const timeoutId = setTimeout(() => {
        if (!connected) {
          socket.destroy();
          resolve(false);
        }
      }, timeout);

      socket.connect(port, ip, () => {
        connected = true;
        clearTimeout(timeoutId);
        socket.destroy();
        resolve(true);
      });

      socket.on("error", () => {
        connected = false;
        clearTimeout(timeoutId);
        socket.destroy();
        resolve(false);
      });
    });
  }
}

module.exports = NetworkDetector;
